var sqlData = {
  databases: ['db1', 'db2', 'test_db'],
  tables: {
    'db1': ['users', 'products'],
    'db2': ['orders', 'customers'],
    'test_db': ['logs', 'events']
  },
  columns: {
    'db1': {
      'users': ['id', 'name', 'email'],
      'products': ['id', 'name', 'price']
    },
    'db2': {
      'orders': ['id', 'user_id', 'total'],
      'customers': ['id', 'name', 'address']
    },
    'test_db': {
      'logs': ['id', 'message', 'created_at'],
      'events': ['id', 'event_name', 'event_time']
    }
  }
}

var sqlCompleter = {
  getCompletions: function(editor, session, pos, prefix, callback) {
    var line = session.getLine(pos.row)
    var currentDatabase = null
    var currentTable = null

    // 解析当前行以获取数据库和表的信息
    var dbMatch = line.match(/FROM\s+(\w+)/i)
    var tableMatch = line.match(/(\w+)\.(\w+)$/)

    // 找到当前数据库
    if (dbMatch) {
      currentDatabase = dbMatch[1]
    }

    // 找到当前表
    if (tableMatch) {
      currentTable = tableMatch[1]
    }

    let completions = []

    // 如果没有指定数据库，显示所有数据库
    if (!currentDatabase) {
      completions = sqlData.databases.map(db => ({
        name: db,
        value: db,
        score: 1000
      }))
    }
    // 如果已指定数据库但未指定表，显示该数据库的所有表
    else if (sqlData.tables[currentDatabase]) {
      if (!currentTable) {
        completions = sqlData.tables[currentDatabase].map(table => ({
          name: table,
          value: table,
          score: 1000
        }))
      }
      // 如果已指定表，显示该表的所有列
      else if (sqlData.columns[currentDatabase] && sqlData.columns[currentDatabase][currentTable]) {
        completions = sqlData.columns[currentDatabase][currentTable].map(column => ({
          name: column,
          value: `${currentTable}.${column}`,
          score: 1000
        }))
      }
    }

    callback(null, completions)
  }
}

editor.setOptions({
  enableBasicAutocompletion: [sqlCompleter],
  enableSnippets: false,
  enableLiveAutocompletion: true
})

/**
 *
 * @param {function(string)} databaseGetter
 * @param {function(string, string)} tableGetter
 * @param {function(string, string, string)} columnGetter
 */
function autocomplete(databaseGetter, tableGetter, columnGetter) {
  const dbs = databaseGetter('dbname')
  const tables = tableGetter('', '')
  const cols = columnGetter('', '', '')
}

export default autocomplete
